package cn.wizzer.app.web.modules.controllers.platform.bus.equipment;

import cn.wizzer.app.bus.modules.models.equipment.BusEquipment;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentProcess;
import cn.wizzer.app.bus.modules.models.equipment.BusEquipmentServicing;
import cn.wizzer.app.bus.modules.services.BusEquipmentProcessService;
import cn.wizzer.app.bus.modules.services.BusEquipmentService;
import cn.wizzer.app.sys.modules.services.SysDictService;
import cn.wizzer.app.sys.modules.services.SysUnitService;
import cn.wizzer.app.sys.modules.services.SysUserService;
import cn.wizzer.app.web.commons.slog.annotation.SLog;
import cn.wizzer.app.web.commons.utils.ShiroUtil;
import cn.wizzer.app.web.commons.utils.StringUtil;
import cn.wizzer.framework.base.Result;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.nutz.aop.interceptor.ioc.TransAop;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;
import org.nutz.lang.util.NutMap;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import org.nutz.mvc.annotation.*;

import javax.servlet.http.HttpServletRequest;
import cn.wizzer.app.bus.modules.services.BusEquipmentServicingService;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 设备维修表
 * @author tcjinxiu.com
 * @time 2024-04-11 10:19:44
 *
 */
@IocBean
@At("/platform/bus/equipment/servicing")
public class BusEquipmentServicingController {
private static final Log log = Logs.get();
	@Inject
	BusEquipmentServicingService busEquipmentServicingService;
	@Inject
	BusEquipmentService busEquipmentService;
	@Inject
	BusEquipmentProcessService busEquipmentProcessService;
	@Inject
	private SysDictService sysDictService;
	@Inject
	private SysUnitService sysUnitService;
	@Inject
	private SysUserService sysUserService;
	@Inject
	private ShiroUtil shiroUtil;

	private static final String type="servicing";
	//private static final int[] EquipmentServicing = {0,1,2,3,4,5,8,9,10};//维修流程"ask department chargeLeader finance leadership complete

	@At("/?")
	@Ok("beetl:/platform/bus/equipment/servicing/index.html")
	@RequiresAuthentication
	public void index(String processName,HttpServletRequest req) {
		//String processCode = sysDictService.getProcessCode(processName);
		req.setAttribute("processName", processName);
		req.setAttribute("userId",StringUtil.getPlatformUid());
		req.setAttribute("userName",shiroUtil.getPrincipalProperty("username").toString());
		Map processMap =sysDictService.getCodeMap("equipmentProcessCode");
		req.setAttribute("processMap", JSONObject.fromObject(processMap));
		req.setAttribute("processOptions", JSONArray.fromObject(busEquipmentProcessService.listThisProcess(processMap, new int[]{0, 1, 2, 3, 4, 5})));
		req.setAttribute("calculateMap", JSONObject.fromObject(sysDictService.getCodeMap("calculate")));
		req.setAttribute("calculateCycleTypeMap", JSONObject.fromObject(sysDictService.getCodeMap("calculateCycleType")));
	}

	@At
	@Ok("json:full")
	@RequiresAuthentication
	public Object data(@Param("code") String code, @Param("name") String name,@Param("lczt") String lczt,@Param("status") String status,
					   @Param("repairStartDate") String repairStartDate, @Param("repairEndDate") String repairEndDate,
					   @Param("processName") String processName,
					   @Param("pageNumber") int pageNumber,@Param("pageSize") int pageSize
			, @Param("pageOrderName") String pageOrderName, @Param("pageOrderBy") String pageOrderBy) {
		try {
			String sql = "select e.code,e.name,e.model,ur.username as managerName,ut.name as applyName,urr.username as opName," +
					"es.id,es.lczt,es.nextspr,es.symptom,es.calibrationFlag,es.repairDate,es.repairUnit,es.repairRemak,FROM_UNIXTIME(es.opAt) as opTime,es.opBy " +
					"from bus_equipment_servicing es " +
					"left join bus_equipment e on es.equipmentId=e.id " +
					"left join sys_user ur on ur.id=e.managerBy " +
					"left join sys_unit ut on ut.id = e.applyDept " +
					"left join sys_user urr on urr.id=es.opBy where es.delFlag=0 ";
			if(StringUtils.isNotBlank(processName)&& processName.equals("audit")){
				sql+= " and es.nextsprIds='"+StringUtil.getPlatformUid()+"' and (es.lczt = 2 or es.lczt = 1)";
			}else if(StringUtils.isNotBlank(processName)&& processName.equals("complete")){
				//sql+= StringUtil.dataScopeFilter("es");
				sql+=  " and es.opBy = '"+StringUtil.getPlatformUid()+"'";
				if(StringUtils.isNotBlank(status)){
					sql+= " and  es.lczt = '"+status+"' ";
				}else{
					sql+= " and  (es.lczt = 4 or es.lczt = 5)  ";
				}
			}else{
				//数据权限
				sql+= StringUtil.dataScopeFilter("es");
			}
			if(StringUtils.isNotBlank(code)){
				sql+= " and  e.code like '%"+code+"%' ";
			}
			if(StringUtils.isNotBlank(name)){
				sql+= " and  e.name like '%"+name+"%' ";
			}
			if(StringUtils.isNotBlank(lczt)){
				sql+= " and  es.lczt = '"+lczt+"' ";
			}
			if(StringUtils.isNotBlank(repairStartDate)){
				sql+= " and  es.repairDate >='"+repairStartDate+"' ";
			}
			if(StringUtils.isNotBlank(repairEndDate)){
				sql+= " and  es.repairDate <='"+repairEndDate+"' ";
			}
			sql="select * from ("+sql+") a";
			if (Strings.isNotBlank(pageOrderName) && Strings.isNotBlank(pageOrderBy)) {
				if ("ascending".equalsIgnoreCase(pageOrderBy)) {
					sql+= " order by "+pageOrderName+" asc,opTime desc ";
				} else {
					sql+= " order by "+pageOrderName+" desc,opTime desc ";
				}
			}else{
				sql+= " order by opTime desc ";
			}
			return Result.success().addData(busEquipmentServicingService.listPage(pageNumber, pageSize, Sqls.create(sql)));
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			return Result.error();
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At
	@Ok("json")
	@RequiresPermissions("equipment.servicing.add")
	@SLog(tag = "Add", msg = "Add:bus_equipment_servicing")
	public Object addDo(@Param("..") BusEquipmentServicing servicing, HttpServletRequest req) {
		try {
			servicing = busEquipmentServicingService.insert(servicing);
			BusEquipmentProcess process = new BusEquipmentProcess();
			process.setHeadId(servicing.getId());
			process.setEquipmentId(servicing.getEquipmentId());
			process.setLczt(servicing.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setNextspr(servicing.getNextspr());
			process.setNextsprIds(servicing.getNextsprIds());
			busEquipmentProcessService.insert(process);
			busEquipmentServicingService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At("/detail/?")
	@Ok("json")
	public Object detail(String id) {
		BusEquipmentServicing servicing = busEquipmentServicingService.fetch(id);
		List listProcess = busEquipmentProcessService.list(Sqls.create("select *,(select username from sys_user where id = es.opBy) as opName,FROM_UNIXTIME(es.opAt) as opTime from  bus_equipment_process es where " +
				" equipmentId='"+servicing.getEquipmentId()+"' and headId='"+servicing.getId()+"' and type='"+type+"' order by opAt desc"));
		NutMap  map = new NutMap();
		map.addv("servicing", servicing);
		map.addv("listProcess", listProcess);
		try {
			return Result.success("system.success").addData(map);
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At
	@Ok("json")
	@RequiresPermissions("equipment.servicing.edit")
	@SLog(tag = "Edit", msg = "Edit:bus_equipment_servicing")
	public Object editDo(@Param("..") BusEquipmentServicing servicing, HttpServletRequest req) {
		try {
			BusEquipmentProcess process = new BusEquipmentProcess();
			process.setHeadId(servicing.getId());
			process.setEquipmentId(servicing.getEquipmentId());
			process.setLczt(servicing.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			process.setNextspr(servicing.getNextspr());
			process.setNextsprIds(servicing.getNextsprIds());
			busEquipmentServicingService.update(servicing);
			busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>=" + servicing.getLczt() + " and headId='" + servicing.getId() + "' and type='" + type + "' "));
			busEquipmentProcessService.insert(process);
			busEquipmentServicingService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At("/subDo/?")
	@Ok("json")
	@RequiresPermissions("equipment.servicing.edit")
	@SLog(tag = "subDo", msg = "subDo:bus_equipment_servicing")
	public Object subDo(String id) {
		try {
			BusEquipmentServicing servicing = busEquipmentServicingService.fetch(id);
			servicing.setLczt("1");
			BusEquipmentProcess process = busEquipmentProcessService.fetch(Cnd.NEW().and("headId", "=", servicing.getId())
					.and("lczt","=","0").and("delflag","=","0").and("type", "=", type));
			process.setHeadId(servicing.getId());
			process.setEquipmentId(servicing.getEquipmentId());
			process.setLczt(servicing.getLczt());
			process.setType(type);
			process.setStatus("0");
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			//busEquipmentService.update(equipment);
			busEquipmentServicingService.update(servicing);
			busEquipmentProcessService.execute(Sqls.create("update bus_equipment_process set delflag=1 where lczt>=" + servicing.getLczt() + " and headId='" + servicing.getId() + "' and type='" + type + "' "));
			busEquipmentProcessService.insert(process);
			busEquipmentServicingService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@Aop(TransAop.READ_COMMITTED)
	@At
	@Ok("json")
	@SLog(tag = "processDo", msg = "processDo:bus_equipment_servicing")
	public Object processDo(@Param("..") BusEquipmentServicing servicing,@Param("..") BusEquipmentProcess process,
							HttpServletRequest req) {
		try {
			BusEquipment equipment = busEquipmentService.fetch(servicing.getEquipmentId());
			if(!servicing.getLczt().equals("5")) {
				if (servicing.getAuditFlag().equals("0")) {
					servicing.setLczt("2");
				} else if (process.getStatus().equals("0")) {
					servicing.setLczt("4");
					servicing.setNextspr(null);
					servicing.setNextsprIds(null);
					process.setNextspr(null);
					process.setNextsprIds(null);
					//最后一级审批通过则进入维修状态
					equipment.setStatus("5");
				} else {
					servicing.setLczt("3");
					servicing.setNextspr(null);
					servicing.setNextsprIds(null);
					process.setNextspr(null);
					process.setNextsprIds(null);
				}
			}else{
				equipment.setStatus("1");
			}
			process.setHeadId(servicing.getId());
			process.setEquipmentId(servicing.getEquipmentId());
			process.setLczt(servicing.getLczt());
			process.setType(type);
			process.setOpBy(StringUtil.getPlatformUid());
			process.setOpAt(Times.getTS());
			busEquipmentService.update(equipment);
			busEquipmentServicingService.update(servicing);
			busEquipmentProcessService.insert(process);
			busEquipmentServicingService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}

	@At({"/delete","/delete/?"})
	@Ok("json")
	@RequiresPermissions("equipment.servicing.delete")
	@SLog(tag = "Delete", msg = "Delete:bus_equipment_servicing")
	public Object delete(String id,@Param("ids") String[] ids, HttpServletRequest req) {
		try {
			if(ids!=null&&ids.length>0){
				busEquipmentServicingService.vDelete(ids);
			}else{
				busEquipmentServicingService.vDelete(id);
			}
			busEquipmentServicingService.clearCache();
			return Result.success("system.success");
		} catch (Exception e) {
			return Result.error("system.error");
		}
	}
}
